package com.minelx.statementsplus.cha.webauto;

import com.minelx.autocha.IWebBrowser;
import com.minelx.autocha.IWebBrowserFactory;
import com.minelx.autocha.WebElements;

import static com.minelx.statementsplus.cha.webauto.ChaPage.URL_HEAD;

public class ChaPageFactory {
	private final String username;

	private final String password;

	private final IWebBrowserFactory driverFactory;

	public ChaPageFactory(IWebBrowserFactory driverFactory, String username, String password) {
		this.username = username;
		this.password = password;
		this.driverFactory = driverFactory;
	}

	public ChaPage createChaPage() {
		IWebBrowser result = driverFactory.createBrowser();
		// do login
		if (isNewWebBrowser(result)) {
			doLogin(result);
		} else { // do refresh
			result.coreDriver().navigate().refresh();
		}
		return new ChaPage(result);
	}

	private boolean isNewWebBrowser(IWebBrowser result) {
		String url = result.coreDriver().getCurrentUrl();
		if (url.equals("data:,")) { // new window
			return true;
		} else if (url.startsWith(URL_HEAD)) {
			return false;
		}
		throw new RuntimeException("something is wrong here: " + url);
	}

	private void doLogin(IWebBrowser result) {
		result.open(URL_HEAD + "/index.html");
		result.id("login_name").sendKeys(username);
		result.id("login_pwd").sendKeys(password);
		result.id("login_btn").click();
		result.selector("body > div.login_con").until(WebElements.attribute("style", "display: none;"));
		System.out.println("ChaPage.ChaPage login success.");
	}
}
